<?php

namespace Admin\Controller;
use Think\Controller;

class IndexController extends Controller{
    public function __construct() {
        //验证是否登录
        parent::__construct();
        if(!session('id')){
            $this->redirect('Admin/Login/login');
        }
        $adminId = session('id');
        //验证当面管理员是否有权限访问页面
      
        
        // 查询数据库判断当前管理员有没有访问这个页面的权限
        $url = MODULE_NAME .'/'. CONTROLLER_NAME . '/' . ACTION_NAME;
        // 查询数据库判断当前管理员有没有访问这个页面的权限
        $where = 'module_name="'.MODULE_NAME.'" AND controller_name="'.CONTROLLER_NAME.'" AND action_name="'.ACTION_NAME.'"';

        // 任何人只要登录了就可以进入后台
        if(CONTROLLER_NAME == 'Index')
            return TRUE;

        if($adminId == 1)
            $sql = 'SELECT COUNT(*) has FROM sp_privilege WHERE '.$where;
        else 
            $sql = 'SELECT COUNT(a.role_id) has
            FROM sp_role_privilege a
            LEFT JOIN sp_privilege b ON a.pri_id=b.id
            LEFT JOIN sp_admin_role c ON a.role_id=c.role_id
            WHERE c.admin_id='.$adminId.' AND '.$where;
        $db = M();
        $pri = $db->query($sql);
        if($pri[0]['has'] < 1)
            $this->error('无权访问！');


    }
    public function index() {
        $this->display();
    }
    public function menu() {
        $adminId = session('id');
        $where = 'module_name="'.MODULE_NAME.'" AND controller_name="'.CONTROLLER_NAME.'" AND action_name="'.ACTION_NAME.'"';
        if($adminId == 1)
            $sql = 'SELECT *  FROM sp_privilege';
        else 
            $sql = 'SELECT b.* 
            FROM sp_role_privilege a
            LEFT JOIN sp_privilege b ON a.pri_id=b.id
            LEFT JOIN sp_admin_role c ON a.role_id=c.role_id
            WHERE c.admin_id='.$adminId;
        $db = M();
        $pri = $db->query($sql);
        $arr = array();
        foreach ($pri as $k=>$v){
            if($v['parent_id']==0){
                foreach ($pri as $k1=>$v1){
                    if($v1['parent_id']==$v['id']){
                        $v['children'][]=$v1;
                    }
                }
                $arr[]=$v;
            }
        }
        $this->assign('arr',$arr);
        $this->display();
    }
    public function top() {
        $this->display();
    }
    public function main() {
        $this->display();
    }
    
    public function setpageBtn($title,$btnName,$btnLink){
    	$this->assign('_page_title',$title);
    	$this->assign('_page_btn_name',$btnName);
    	$this->assign('_page_btn_link',$btnLink);
    }
}
